import { t } from 'i18next'
import React, { useEffect, useState } from 'react'
import { getRateList, isIpInSelected, SelectedMt, SelectedMtModel } from '../../../../translator'
import { Avatar } from '@/components/Avatar'
import { StyledWrap, StyledMoreWrap, StyledOptionWrap, StyledCallType } from './style'
import {
	IconAvatarTip,
	IconCheckbox,
	IconBigRightWhite,
	IconBigLeftWhite,
	IconStar,
	IconPhoneCallBlack,
	IconVideoCallBlack,
	IconAudioCallBlack,
} from '../../../../components/Icons'
import { CONSTANT } from '../../../../utils/utils'
import { InputNumber, Select } from '@kedacom/react-next'
import { useMtAddStore } from '../../../../store'
import shallow from 'zustand/shallow'
import { useSelectedStore } from '../../store'
import { useGlobalStore } from '@/store/global'

interface ListItemProps {
	data: SelectedMtModel
}

const PROTOCOL_TYPES = [
	{
		id: CONSTANT.callType.RTC,
		name: 'RTC',
	},
	{
		id: CONSTANT.callType.SIP,
		name: 'SIP',
	},
	{
		id: CONSTANT.callType.H323,
		name: 'H323',
	},
	{
		id: CONSTANT.callType.AUTO,
		name: 'AUTO',
	},
]

//呼叫协议
const ItemProtocol = ({ data }: ListItemProps) => {
	const { item } = data
	const isSupportRtc = useMtAddStore((state) => state.isSupportRtc)
	const changeProtocol = useSelectedStore((state) => state.changeProtocol)
	//ip协议 仅SIP 323 Auto。其他的全都有，但不支持RTC时，也不显示RTC协议
	const list = isIpInSelected(data) || !isSupportRtc ? PROTOCOL_TYPES.filter((x) => x.name !== 'RTC') : PROTOCOL_TYPES
	return (
		<StyledOptionWrap className="option">
			<Select
				width={65}
				valueField="id"
				labelField="name"
				options={list}
				value={item.protocol}
				onChange={(e, val) => {
					changeProtocol(item, val)
				}}
			/>
		</StyledOptionWrap>
	)
}
//呼叫码率
const ItemRate = ({ data }: ListItemProps) => {
	const { item } = data
	const maxRate = useMtAddStore((state) => state.maxRate)
	const { changeRateBySelect, changeRateByInput } = useSelectedStore(
		(state) => ({
			changeRateBySelect: state.changeRateBySelect,
			changeRateByInput: state.changeRateByInput,
		}),
		shallow
	)
	const [inputVal, setInputVal] = useState(item.bitrate + '')
	useEffect(() => {
		setInputVal(item.bitrate + '')
	}, [item.bitrate])
	return (
		<>
			<StyledOptionWrap className="option">
				<Select
					width={65}
					valueField="id"
					labelField="name"
					value={item.bitrateType}
					options={getRateList(maxRate)}
					onChange={(e, val) => {
						changeRateBySelect(item, val)
					}}
				/>
			</StyledOptionWrap>
			{item.bitrateType === 0 && (
				<StyledOptionWrap className="option bitrate-input">
					<InputNumber
						maxLength={128}
						width={38}
						value={inputVal}
						onChange={(e, value) => {
							setInputVal(value)
						}}
						onBlur={(e, value) => {
							changeRateByInput(item, value)
						}}
					/>
					<span className="unit">Kbps</span>
				</StyledOptionWrap>
			)}
		</>
	)
}
const CALL_TYPES = [
	{
		value: 'phone',
		label: <IconPhoneCallBlack className="phone-type" />,
	},
	{
		value: 'video',
		label: <IconVideoCallBlack className="video-type" />,
	},
	{
		value: 'audio',
		label: <IconAudioCallBlack className="audio-type" />,
	},
]
//呼叫方式      64码率代表音频呼叫，accountType为phone是手机呼叫，其他是视频呼叫
const ItemCallType = ({ data }: ListItemProps) => {
	const { item } = data
	const changeCallType = useSelectedStore((state) => state.changeCallType)
	const itemRender = (id: string, active: boolean) => {
		return (
			<StyledCallType isActive={active}>
				{id === CALL_TYPES[0].value && CALL_TYPES[0].label}
				{id === CALL_TYPES[1].value && CALL_TYPES[1].label}
				{id === CALL_TYPES[2].value && CALL_TYPES[2].label}
			</StyledCallType>
		)
	}
	const getCallTypes = (user: SelectedMt) => {
		let result = CALL_TYPES.filter((x) => x.value !== 'phone')
		if (user.accountType === CONSTANT.accountType.phone || user.mobilePhone || user.workPhone) {
			result = [...CALL_TYPES]
		}
		return result
	}
	const actualVal =
		item.bitrate === 64 ? 'audio' : item.accountType === CONSTANT.accountType.phone ? 'phone' : 'video'
	return (
		<StyledOptionWrap className="option call-type">
			<Select
				optionRender={(op, selected) => itemRender(op.value, selected)}
				options={getCallTypes(item)}
				width={38}
				onChange={(e, val) => {
					changeCallType(item, val)
				}}
				value={actualVal}
			></Select>
		</StyledOptionWrap>
	)
}
function MoreOptions({ data }: ListItemProps) {
	const showProtocol = data.item.accountType !== CONSTANT.accountType.phone
	return (
		<StyledMoreWrap className="more-wrap" onClick={(e) => e.stopPropagation()}>
			{showProtocol && <ItemProtocol data={data} />}
			<ItemRate data={data} />
			<ItemCallType data={data} />
		</StyledMoreWrap>
	)
}
export function ListItem({ data }: ListItemProps) {
	const { item, attr, status } = data
	const { meetingType, isSuperMeeting, isOnlyMakeUser } = useMtAddStore(
		(state) => ({
			meetingType: state.meetingType,
			isSuperMeeting: state.isSuperMeeting,
			isOnlyMakeUser: state.isOnlyMakeUser,
		}),
		shallow
	)
	const SWITCH = useGlobalStore((state) => state.SWITCH)
	const { clickSelectItem, checkSelectItem, changeItemType, toggleMoreOpt, removeItem } = useSelectedStore(
		(state) => ({
			clickSelectItem: state.clickSelectItem,
			checkSelectItem: state.checkSelectItem,
			changeItemType: state.changeItemType,
			toggleMoreOpt: state.toggleMoreOpt,
			removeItem: state.removeItem,
		}),
		shallow
	)
	const avatarValue = {
		portrait: item.portrait,
		accountType: item.accountType,
	}
	const starTitle = isSuperMeeting
		? attr.isInteractiveMt
			? t('取消互动终端')
			: t('设置互动终端')
		: attr.isOftenMt
		? t('取消常用终端')
		: t('设置常用终端')
	const canShowIconTip = isSuperMeeting ? attr.isInteractiveMt : attr.isOftenMt
	/** 是否显示五角星 */
	const canShowIcon = isSuperMeeting || !!SWITCH.showOftenMt ? true : false

	const handleClick = (e: React.MouseEvent) => {
		clickSelectItem(data, { ctrlKey: e.ctrlKey, shiftKey: e.shiftKey })
	}
	const handleDblClick = () => {
		removeItem(data)
	}
	const handleCheck = (e: React.MouseEvent) => {
		e.stopPropagation()
		checkSelectItem(data)
	}
	const handleChangeItemType = (e: React.MouseEvent) => {
		e.stopPropagation()
		changeItemType(data)
	}
	const handleOpenMoreOpt = (e: React.MouseEvent) => {
		e.stopPropagation()
		toggleMoreOpt(data)
	}
	const handleCloseMoreOpt = (e: React.MouseEvent) => {
		e.stopPropagation()
		toggleMoreOpt(data)
	}

	return (
		<StyledWrap isSelected={status.isSelected} onClick={handleClick} onDoubleClick={handleDblClick}>
			<div className="icon-wrap" onClick={handleCheck}>
				<IconCheckbox className="icon-check-box" />
			</div>
			<div className="item-content">
				<Avatar value={avatarValue} size={24} />
				{canShowIconTip && canShowIcon && <IconAvatarTip className="avatar-tip" />}
				<div className="item-name" title={item.name}>
					{item.name}
				</div>
			</div>
			<div className="item-type">
				{!status.isOpenMoreOpt && !isOnlyMakeUser && canShowIcon && (
					<IconStar title={starTitle} flag={canShowIconTip} onClick={handleChangeItemType} />
				)}
			</div>
			<div className="more-options">
				{!status.isOpenMoreOpt && meetingType !== 2 && !isOnlyMakeUser && (
					<IconBigLeftWhite onClick={handleOpenMoreOpt} />
				)}
				{status.isOpenMoreOpt && (
					<>
						<IconBigRightWhite className="icon-right" onClick={handleCloseMoreOpt} />
						<MoreOptions data={data} />
					</>
				)}
			</div>
		</StyledWrap>
	)
}
